package net

import (
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

// 封装一个游戏服务器
// 目前只支持websocket，之后拓展http路由提供集卡组的功能
type game_server struct {
	upgrader websocket.Upgrader
}

func (s *game_server) init() {
	s.upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
}

func (s *game_server) run() {
	http.HandleFunc("/ws", handleWebSocket)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// 服务器需要对客户端的请求频率进行设置
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	// 身份验证
	token := r.URL.Query().Get("token")
	userID, err := auth.VerifyToken(token)
	if err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	// 升级WebSocket连接
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("WebSocket升级失败:", err)
		return
	}

	// 分配一个session

	// 启动读写协程
	go session.ReadPump()
	go session.WritePump()
}
